package com.cdtu.utils;

import ch.qos.logback.core.util.FileUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * @author Mika
 * @date 2025/02/28 15:11
 * 文件工具类
 **/
public class FileUtils {

    private static final Logger log = LoggerFactory.getLogger(FileUtils.class);
    static ClassLoader classLoader = FileUtil.class.getClassLoader();
    
    public static JsonNode getJsonData(String fileName) {
        JsonNode jsonNode;
        try (InputStream inputStream = loadResourceStream(fileName)) {
            ObjectMapper mapper = new ObjectMapper();
            jsonNode = mapper.readTree(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return jsonNode;
    }

    public static Path loadResource(String fileName) {
        URL resource = classLoader.getResource(fileName);
        try {
            return Paths.get(resource.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public static InputStream loadResourceStream(String fileName) {
        return classLoader.getResourceAsStream(fileName);
    }

    public static String getProp(String property) {
        Properties properties = new Properties();
        String fileName = "EventType.properties";
        try {
            InputStream inputStream = loadResourceStream(fileName);
            if (inputStream == null) {
                log.error("没有找到 {} 文件", fileName);
                return null;
            }
            properties.load(inputStream);
            return properties.getProperty(property);
        } catch (IOException e) {
            log.error("在 {} 文件中加载 {} 配置项失败", property, fileName);
            throw new RuntimeException(e);
        }

    }
}
